<template>
  <div class="redirect-container">
    <el-card class="box-card">
      <el-form
        ref="userDataRef"
        :model="userData"
        label-width="80px"
        :rules="rules"
        auto-complete="on"
        label-position="left"
      >
        <div style="width: 40px; margin: 0 auto">
          <h3 style="align-content: center">注册</h3>
        </div>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userData.username"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="userData.password" type="password"></el-input>
        </el-form-item>

        <el-form-item label="确认密码" prop="checkPassword">
          <el-input v-model="userData.checkPassword" type="password"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userData.email"></el-input>
        </el-form-item>

        <el-form-item label="验证码" prop="checkCode">
          <el-row :gutter="10">
            <el-col :span="12">
              <el-input v-model="userData.checkCode"> </el-input
            ></el-col>
            <el-col :span="8">
              <el-button
                :loading="codeLoading"
                :disabled="isDisable"
                size="small"
                round
                @click="sendMsg"
                >发送验证码</el-button
              >
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              {{ statusMsg }}
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSubmit" :loading="loading"
            >立即注册</el-button
          >
          <el-button @click="$router.push('/login')">返回登录页面</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import userApi from "@/api/userManage";
import Axios from "axios";

export default {
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "" || value === undefined) {
        callback(new Error("请输入密码"));
      } else if (value.length < 6 || value.length > 20) {
        callback(new Error("密码长度不能小于6位或超过20位"));
      } else {
        if (this.userData.checkPassword !== "") {
          this.$refs.userDataRef.validateField("checkPassword");
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "" || value === undefined) {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.userData.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };

    var validateEmail = (rule, value, callback) => {
      var reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
      if (value === "" || value === undefined) {
        callback(new Error("请输入邮箱"));
      } else if (!reg.test(value)) {
        callback(new Error("请输入正确的邮箱验证规则,例如(xxx@aliyun.com)"));
      } else {
        callback();
      }
    };

    return {
      loading: false,
      userData: {},
      user: {},
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 2,
            max: 20,
            message: "长度在 2 到 20 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, validator: validatePass, trigger: "blur" },
        ],
        checkPassword: [
          { required: true, validator: validatePass2, trigger: "blur" },
        ],
        email: [{ required: true, validator: validateEmail, trigger: "blur" }],
      },

      flag: true,

      codeYes: "",
      statusMsg: "",
    };
  },
  methods: {
    sendMsg: function () {
      const self = this;

      let timerid;
      if (timerid) {
        return false;
      }
      self.statusMsg = "";

      // 向后台API验证码发送

      this.$refs["userDataRef"].validate((valid) => {
        if (valid) {
          self.codeLoading = true;
          self.statusMsg = "验证码发送中...";

          let data = {
            email: self.userData.email,
            message: "FStart:注册验证码",
          };
          userApi
            .getEmailCode(data)
            .then((res) => {
              this.$message({
                showClose: true,
                message: "发送成功，验证码有效期5分钟",
                type: "success",
              });
              let count = 60;
              self.userData.code = "";
              self.codeLoading = false;
              self.isDisable = true;
              self.statusMsg = `验证码已发送,${count--}秒后重新发送`;
              timerid = window.setInterval(function () {
                self.statusMsg = `验证码已发送,${count--}秒后重新发送`;
                if (count <= 0) {
                  window.clearInterval(timerid);
                  self.isDisable = false;
                  self.statusMsg = "";
                }
              }, 1000);
            })
            .catch((err) => {
              console.log(err.response);
              this.isDisable = false;
              this.statusMsg = "";
              this.codeLoading = false;
              console.log(err.response.data.message);
            });
        } else {
          this.$message({
            message: "请输入正确的注册信息哦！",
            type: "warning",
          });
          return false;
        }
      });
    },

    // 提交表单
    onSubmit() {
      this.$refs["userDataRef"].validate((valid) => {
        if (valid) {
          this.loading = true;
          this.user.username = this.userData.username;
          this.user.password = this.userData.password;
          this.user.email = this.userData.email;
          this.user.checkCode = this.userData.checkCode;

          userApi
            .register(this.user)
            .then((resp) => {
              this.$message({
                message: resp.message,
                type: "success",
              });
              if (resp.code === 20000) {
                this.$router.push("/login");
              }

              this.loading = false;
            })
            .catch((err) => {
              console.log(err.response);
              this.isDisable = false;
              this.statusMsg = "";
              this.loading = false;
              console.log(err.response.data.message);
            });
        } else {
          this.$message({
            message: "请输入正确的注册信息哦！",
            type: "warning",
          });
          return false;
        }
      });
    },
  },
};
</script>

<style>
.redirect-container {
  min-height: 100%;
  width: 100%;

  overflow: hidden;

  display: flex;
  align-items: center;
}
.box-card {
  width: 450px;
  margin: 0 auto;
  /* margin-top: 9%; */
}
</style>
